import { Controller, Get, Post, Query, Body, Res, Req } from '@nestjs/common'
import { Response, Request } from 'express'
import { ApiTags, ApiOperation } from '@nestjs/swagger'
import { WechatService } from './wechat.service'
import { getStream, jsonToWechatXml } from '../common'
import { parseStringPromise } from 'xml2js'
import { SignatureDto, SendTemplateInput } from './dto'

@Controller('wechat')
@ApiTags('微信公众号')
export class WechatController {
  constructor(private readonly wechatService: WechatService) {}

  @Get()
  @ApiOperation({ summary: '配置服务器URL、签名校验接口' })
  getMsg(@Query() params: SignatureDto, @Res() res: Response): any {
    console.log('收到微信签名', params)
    const { timestamp, nonce, signature, echostr } = params
    const result = this.wechatService.checkSignature(timestamp, nonce, signature, echostr)
    res.send(result)
  }

  @Post()
  @ApiOperation({ summary: '接收消息自动回复' })
  async getMsgPost(
    @Query() params: any,
    @Body() body: any,
    @Res() res: Response,
    @Req() req: Request
  ): Promise<any> {
    const { timestamp, nonce, signature, echostr } = params
    const result = this.wechatService.checkSignature(timestamp, nonce, signature, echostr)
    console.log('receive message post', params, body)
    if (echostr === result) {
      const buff = await getStream(req)
      const json = await parseStringPromise(buff.toString())
      console.log('收到微信用户消息', params.openid)
      console.log(json)
      // 自动回复测试
      const autoTest = {
        ToUserName: json.xml.FromUserName[0],
        FromUserName: json.xml.ToUserName[0],
        CreateTime: Date.now(),
        MsgType: 'text',
        Content: `收到消息：${json.xml.Content[0]}`,
      }
      const str = jsonToWechatXml(autoTest)
      res.send(str)
    } else {
      res.send('signature error')
    }
  }

  @Get('getToken')
  @ApiOperation({ summary: '获取access_token' })
  getAccessToken(): any {
    return this.wechatService.getAccessToken()
  }

  @Get('getServersIP')
  @ApiOperation({ summary: '获取微信服务器IP地址' })
  async getServersIP(): Promise<any> {
    const { accessToken } = await this.wechatService.getAccessToken()
    const res = await this.wechatService.getServersIP(accessToken)
    return res
  }

  @Post('sendTemplate')
  @ApiOperation({ summary: '模板消息（业务通知）' })
  async sendTemplate(@Body() inputData: SendTemplateInput) {
    const { accessToken } = await this.wechatService.getAccessToken()
    return this.wechatService.sendTemplate({
      accessToken,
      // touser: 'ovfAXv3RfIX6GCONy2v-g0h7oJ6M',
      touser: inputData.touser,
      template_id: '6mcN23V5s4dutuYkBAVK9Q3aZskS9VRvD997rVOyPAU',
      productType: inputData.productType,
      name: inputData.name,
      number: inputData.number,
      expDate: inputData.expDate,
      remark: inputData.remark,
    })
  }

  @Get('getTicket')
  @ApiOperation({ summary: '初始化jssdk（待优化）' })
  async getTicket(@Req() req: Response) {
    const url = req.header('referer')
    const { accessToken } = await this.wechatService.getAccessToken()
    return this.wechatService.getTicket(accessToken, url)
  }
}
